package com.tistory.commons.utils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ListWriterUtil {

    protected static Log logger = LogFactory.getLog(ListWriterUtil.class);

    public static void writeXML( JspWriter out, ArrayList contentList, ArrayList headerList, String tableWidth )
            throws Exception {
        try {
            Map listMap = null;
            Map headerMap = null;
            Object fieldValue = null;

            logger.debug("##### contentList.size() : " + contentList.size());

            out.println("<?xml version=\"1.0\" encoding=\"euc-kr\"?>");
            out.print("<rows");
            if (tableWidth != null && "" != tableWidth)
                out.println(" wd=\"" + tableWidth + "\">");
            else
                out.println(">");

            for (int i = 0; i < contentList.size(); i++) {
                listMap = (Map)contentList.get(i);
                out.println("\t<row id=\"" + i + "\">");

                for (int j = 0; j < headerList.size(); j++) {
                    headerMap = (Map)headerList.get(j);

                    out.print("\t\t<col ix=\"" + j + "\"");

                    if (headerMap.get("keyField") != null && !"".equals(headerMap.get("keyField")))
                        out.print(" cd=\""
                                + (listMap.get(headerMap.get("fieldName")) == null ? ""
                                        : listMap.get(headerMap.get("fieldName")).toString()) + "\"");

                    if (headerMap.get("width") != null && !"".equals(headerMap.get("width")))
                        out.print(" wd=\"" + headerMap.get("width").toString() + "\"");

                    if (headerMap.get("hidden") != null && !"".equals(headerMap.get("hidden")))
                        out.print(" hd=\"1\"");

                    if (headerMap.get("stringValue") != null && !"".equals(headerMap.get("stringValue")))
                        out.print(" link=\"" + (headerMap.get("link") == null ? "" : headerMap.get("link").toString())
                                + "\"");

                    out.print(">");

                    // if (headerMap.get("groupCode") != null &&
                    // !"".equals(headerMap.get("groupCode"))) {
                    // // logger.debug("###groupCode : " +
                    // // headerMap.get("groupCode"));
                    // out.println(normalize(StringUtil.convertNull(CodeManager.getInstance()
                    // .getNameOf(
                    // (String)headerMap.get("groupCode"),
                    // listMap.get((String)headerMap.get("fieldName")) == null ?
                    // ""
                    // :
                    // listMap.get((String)headerMap.get("fieldName")).toString())))
                    // + "</col>");
                    // }
                    // else if (headerMap.get("codeList") != null) {
                    // // logger.debug("###codeList : " +
                    // // headerMap.get("codeList"));
                    // out.println(normalize(StringUtil.convertNull(getCodeValue(
                    // listMap.get((String)headerMap.get("fieldName")),
                    // headerMap.get("codeList"))))
                    // + "</col>");
                    // }
                    // else
                    if (headerMap.get("stringValue") != null && !"".equals(headerMap.get("stringValue"))) {
                        // logger.debug("###fieldName : " +
                        // headerMap.get("fieldName"));
                        // Added By DH Bae, Must normalize raw date to convert,
                        // ex) xml; & to &amp;, < to &lt; ...
                        out.println(normalize((String)headerMap.get("stringValue")) + "</col>");
                    }
                    else {
                        fieldValue = listMap.get(headerMap.get("fieldName"));

                        if (headerMap.get("format") != null && !"".equals(headerMap.get("format"))
                                && fieldValue != null)
                            fieldValue = formatValue(fieldValue, (String)headerMap.get("format"));

                        // logger.debug("###fieldName : " +
                        // headerMap.get("fieldName"));
                        out.println(normalize(fieldValue == null ? "" : fieldValue.toString()) + "</col>");
                    }
                }
                out.println("\t</row>");

            }
            out.print("</rows>");
        }
        catch (Exception e) {
            logger.debug(e.getMessage(), e);
            throw new Exception(e.getMessage(), e);
        }
    }

    public static void writeXML( JspWriter out, ArrayList contentList, ArrayList headerList ) throws Exception {
        writeXML(out, contentList, headerList, null);
    }

    public static Object formatValue( Object value, String format ) throws Exception {
        String returnValue = null;

        if (format.equals("date")) {
            if (value.getClass().equals(String.class)) {
                if (value.toString().length() >= 8) {
                    returnValue = DateUtil.fmtDate(value.toString().substring(0, 8), "yyyyMMdd", "yyyy-MM-dd");
                }
                else
                    returnValue = (String)value;
            }
            else {
                returnValue = DateUtil.getDateStr((Date)value, "-");
            }
        }
        else if (format.equals("number")) {
            NumberFormat form = NumberFormat.getIntegerInstance();
            returnValue = form.format(value);
        }
        else if (format.equals("percent")) {
            DecimalFormat dform = (DecimalFormat)DecimalFormat.getPercentInstance();
            dform.applyPattern("#,##0.00");
            // returnValue =
            // dform.format(Double.parseDouble(value.toString())/100);
            returnValue = dform.format(value);
        }
        else if (format.equals("percent2")) {
            DecimalFormat dform = (DecimalFormat)DecimalFormat.getPercentInstance();
            dform.applyPattern("###");
            // returnValue =
            // dform.format(Double.parseDouble(value.toString())/100);
            returnValue = dform.format(value);
        }
        else if (format.equals("ssn")) {
            if (value != null && value.toString().length() >= 6)
                returnValue = value.toString().substring(0, 6) + "-*******";
            else
                returnValue = "";
        }
        else if (format.equals("card")) {
            if (value != null && value.toString().length() >= 12)
                returnValue = value.toString().substring(0, 4) + "-" + value.toString().substring(4, 8) + "-"
                        + value.toString().substring(8, 12) + "-****";
            else
                returnValue = "";
        }
        else if (format.equals("mdn")) {
            if (value != null && value.toString().length() >= 10) {
                String temp = value.toString();
                returnValue = temp.substring(0, 3) + "-" + temp.substring(3, temp.length() - 4) + "-"
                        + temp.substring(temp.length() - 4, temp.length());
            }
            else
                returnValue = (String)value;
        }
        else if (format.equals("money")) {
            NumberFormat dform = new DecimalFormat("#,##0.##");
            if (value != null)
                returnValue = dform.format(Integer.parseInt(value.toString()));
        }
        else if (format.equals("money2")) {
            NumberFormat dform = new DecimalFormat("#,##0.##");
            if (value != null)
                returnValue = dform.format(value);
        }
        return (Object)returnValue;
    }

    public static String getCodeValue( Object code, Object codeList ) throws Exception {
        List codes = (List)codeList;
        Map recordMap = null;
        String value = "";

        // logger.debug("##### codes.size() : " + codes.size());

        if (code != null) {
            for (int i = 0; i < codes.size(); i++) {
                recordMap = (Map)codes.get(i);

                if (recordMap.get("value").equals(code.toString())) {
                    value = recordMap.get("label").toString();
                    break;
                }
            }
        }

        return value;

    }

    /**
     * @param strInput
     * @return
     * @author harris
     */
    public static String normalize( String strInput ) {
        StringBuffer str = new StringBuffer();

        int len = (strInput != null) ? strInput.length() : 0;

        for (int i = 0; i < len; i++) {
            char ch = strInput.charAt(i);

            switch (ch) {
                case '<':
                    str.append("&lt;");
                    break;
                case '>':
                    str.append("&gt;");
                    break;
                case '&':
                    str.append("&amp;");
                    break;
                case '"':
                    str.append("&quot;");
                    break;
                case '\r':
                    break;
                case '\n':
                default:
                    str.append(ch);
            }
        }

        return (str.toString());
    }

    /**
     * 원하는 길이로(byte) 문장을 자른다.
     * 
     * @param title
     * @param MaxLenth
     * @return
     * @author 최정은
     */
    public static String cutTitle( String title, int MaxLenth ) {
        String newTitle = title;

        try {
            if (newTitle != null && newTitle.length() > 0) {
                byte[] bt = title.getBytes();
                int len = bt.length;

                int count = 0;
                int start = 0;
                int end = MaxLenth;

                int substart = 0;
                int subend = 0;

                substart = substart + subend;
                if (len > MaxLenth)
                    end = start + MaxLenth;
                else
                    end = bt.length;

                count = 0;
                for (int i = start; i < end; i++) {
                    if (bt[i] < 0)
                        count++;
                }

                subend = end - count - start + count / 2;

                len = len - end + start;

                start = end;

                if (count % 2 != 0)
                    start--;

                newTitle = title.substring(substart, substart + subend);
                if (title.length() != newTitle.length())
                    newTitle = newTitle + "...";
            }
            else
                newTitle = "";
        }
        catch (Exception e) {
            logger.debug(e.getMessage(), e);
            return null;
        }

        return newTitle;

    }

    public static String getDate( int i ) {
        Calendar cal = Calendar.getInstance();
        DecimalFormat f2 = new DecimalFormat("00");
        DecimalFormat f3 = new DecimalFormat("000");
        String sThisTime = "";
        sThisTime = cal.get(Calendar.YEAR) + f2.format(cal.get(Calendar.MONTH) + i)
                + f2.format(cal.get(Calendar.DAY_OF_MONTH));
        return sThisTime;
    }

}
